<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="学号" prop="num">
        <el-input
          v-model="queryParams.num"
          placeholder="请输入学号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="姓名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入姓名"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="项目名称" prop="program">
        <el-input
          v-model="queryParams.program"
          placeholder="请输入项目名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-input
          v-model="queryParams.className"
          placeholder="请输入班级"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:student:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:student:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:student:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:student:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          v-hasPermi="['system:student:import']"
        >导入</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="studentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" />
      <el-table-column label="学号" align="center" prop="num" />
      <el-table-column label="姓名" align="center" prop="name" />
      <el-table-column label="项目名称" align="center" prop="program" :show-overflow-tooltip="true" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="联系方式" align="center" prop="way" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:student:query']"
          >查看详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:student:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:student:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改学生信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学号" prop="num">
              <el-input v-model="form.num" placeholder="请输入学号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="program">
              <el-input v-model="form.program" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="班级" prop="className">
              <el-input v-model="form.className" placeholder="请输入班级" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="联系方式" prop="way">
              <el-input v-model="form.way" placeholder="请输入联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 项目描述富文本编辑器 -->
        <el-form-item label="项目描述">
          <div id="editor" style="height: 300px;"></div>
        </el-form-item>
        
        <!-- 图片上传 -->
        <el-form-item label="项目图片">
          <el-upload
            class="upload-demo"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <el-button size="small" type="primary">点击上传图片</el-button>
          </el-upload>
          <div v-if="form.pic" style="margin-top: 10px;">
            <img :src="form.pic" style="max-width: 200px; max-height: 150px;" />
            <el-button size="mini" type="danger" @click="removeImage" style="margin-left: 10px;">删除图片</el-button>
          </div>
        </el-form-item>
        
        <!-- 视频上传 -->
        <el-form-item label="项目视频">
          <el-upload
            class="upload-demo"
            :action="uploadVideoUrl"
            :headers="uploadHeaders"
            :on-success="handleVideoSuccess"
            :before-upload="beforeVideoUpload"
            :show-file-list="false"
            accept="video/*"
          >
            <el-button size="small" type="primary">点击上传视频</el-button>
          </el-upload>
          <div v-if="form.video" style="margin-top: 10px;">
            <video :src="form.video" controls style="max-width: 300px; max-height: 200px;"></video>
            <el-button size="mini" type="danger" @click="removeVideo" style="margin-left: 10px;">删除视频</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 学生详情对话框 -->
    <el-dialog title="学生详情" :visible.sync="viewOpen" width="600px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学号">{{ viewData.num }}</el-descriptions-item>
        <el-descriptions-item label="姓名">{{ viewData.name }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ viewData.program }}</el-descriptions-item>
        <el-descriptions-item label="班级">{{ viewData.className }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ viewData.way }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(viewData.createTime) }}</el-descriptions-item>
      </el-descriptions>
      
      <div v-if="projectDescription" style="margin-top: 20px;">
        <h4>项目描述：</h4>
        <div v-html="projectDescription.description" style="border: 1px solid #dcdfe6; padding: 10px; border-radius: 4px; min-height: 100px;"></div>
      </div>
      
      <div v-if="viewData.pic" style="margin-top: 20px;">
        <h4>项目图片：</h4>
        <img :src="viewData.pic" style="max-width: 100%; max-height: 300px;" />
      </div>
      
      <div v-if="viewData.video" style="margin-top: 20px;">
        <h4>项目视频：</h4>
        <video :src="viewData.video" controls style="max-width: 100%; max-height: 300px;"></video>
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewOpen = false">关 闭</el-button>
      </div>
    </el-dialog>

    <!-- 学生导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <div class="el-upload__tip" slot="tip">
            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的学生数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listStudent, getStudent, delStudent, addStudent, updateStudent, exportStudent, importTemplate, getStudentDescription, saveStudentDescription } from "@/api/system/student";
import { getToken } from "@/utils/auth";

export default {
  name: "Student",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生信息表格数据
      studentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示查看弹出层
      viewOpen: false,
      // 查看数据
      viewData: {},
      // 项目描述
      projectDescription: null,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        num: null,
        name: null,
        program: null,
        className: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        num: [
          { required: true, message: "学号不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ]
      },
      // 上传参数
      upload: {
        // 是否显示弹出层（学生导入）
        open: false,
        // 弹出层标题（学生导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的学生数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: ""
      },
      // 富文本编辑器
      editor: null,
      // 上传地址
      uploadUrl: "",
      uploadVideoUrl: "",
      uploadHeaders: { Authorization: "Bearer " + getToken() }
    };
  },
  created() {
    // 设置上传地址
    const baseApi = process.env.VUE_APP_BASE_API || '/dev-api';
    this.upload.url = baseApi + "/system/student/importData";
    this.uploadUrl = baseApi + "/system/student/uploadImage";
    this.uploadVideoUrl = baseApi + "/system/student/uploadVideo";
    this.getList();
  },
  methods: {
    /** 查询学生信息列表 */
    getList() {
      this.loading = true;
      listStudent(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.studentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        num: null,
        name: null,
        program: null,
        className: null,
        way: null,
        video: null,
        pic: null
      };
      this.resetForm("form");
      if (this.editor) {
        this.editor.setContent('');
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加学生信息";
      this.$nextTick(() => {
        this.initEditor();
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getStudent(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改学生信息";
        this.$nextTick(() => {
          this.initEditor();
          this.loadProjectDescription();
        });
      });
    },
    /** 查看详情操作 */
    handleView(row) {
      this.viewData = row;
      this.viewOpen = true;
      this.loadProjectDescriptionForView(row.id);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 获取富文本内容
          if (this.editor) {
            const description = this.editor.getContent();
            if (description && description.trim()) {
              this.saveProjectDescription(description);
            }
          }
          
          if (this.form.id != null) {
            updateStudent(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStudent(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除学生信息编号为"' + ids + '"的数据项？').then(function() {
        return delStudent(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/student/export', {
        ...this.queryParams
      }, `student_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "学生信息导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/student/importTemplate', {}, `student_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 图片上传成功
    handleImageSuccess(response, file, fileList) {
      this.form.pic = response.data;
      this.$modal.msgSuccess("图片上传成功");
    },
    // 视频上传成功
    handleVideoSuccess(response, file, fileList) {
      this.form.video = response.data;
      this.$modal.msgSuccess("视频上传成功");
    },
    // 图片上传前检查
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/');
      if (!isImage) {
        this.$modal.msgError('只能上传图片文件!');
        return false;
      }
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$modal.msgError('上传图片大小不能超过 10MB!');
        return false;
      }
      return true;
    },
    // 视频上传前检查
    beforeVideoUpload(file) {
      const isVideo = file.type.startsWith('video/');
      if (!isVideo) {
        this.$modal.msgError('只能上传视频文件!');
        return false;
      }
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isLt100M) {
        this.$modal.msgError('上传视频大小不能超过 100MB!');
        return false;
      }
      return true;
    },
    // 删除图片
    removeImage() {
      this.form.pic = null;
    },
    // 删除视频
    removeVideo() {
      this.form.video = null;
    },
    // 初始化富文本编辑器
    initEditor() {
      this.$nextTick(() => {
        if (typeof window.tinymce !== 'undefined') {
          this.editor = window.tinymce.init({
            selector: '#editor',
            height: 300,
            language: 'zh_CN',
            plugins: 'advlist autolink lists link image charmap print preview anchor searchreplace visualblocks code fullscreen insertdatetime media table paste code help wordcount',
            toolbar: 'undo redo | formatselect | bold italic backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | removeformat | help',
            content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
          });
        }
      });
    },
    // 加载项目描述
    loadProjectDescription() {
      if (this.form.id) {
        getStudentDescription(this.form.id).then(response => {
          if (response.data && this.editor) {
            this.editor.setContent(response.data.description || '');
          }
        });
      }
    },
    // 为查看页面加载项目描述
    loadProjectDescriptionForView(studentId) {
      getStudentDescription(studentId).then(response => {
        this.projectDescription = response.data;
      });
    },
    // 保存项目描述
    saveProjectDescription(description) {
      if (this.form.id) {
        const data = {
          studentId: this.form.id,
          studentNum: this.form.num,
          description: description
        };
        saveStudentDescription(data).then(response => {
          // 保存成功，不需要额外处理
        });
      }
    }
  }
};
</script>

<style scoped>
.upload-demo {
  margin-bottom: 10px;
}
</style>
